package com.example.exceptionHandler;

import com.example.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.SocketTimeoutException;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handle(Exception e) {
        log.error("服务器发生异常", e);
        if (e.getMessage().contains("Operation not allowed. The device is not online.")) {
            return Result.error("设备已离线!");
        }
        if (e.getMessage().contains("The access token has expired.")) {
            return Result.error("The access token has expired");
        }
        return Result.error(e.getMessage());
    }

    /**
     * 唯一属性重复异常
     */
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("服务器发生异常", e);
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errMsg = message.substring(i);
        String[] arr = errMsg.split(" ");

        return Result.error(arr[2] + "已存在");
    }

    /**
     * 超时异常
     */
    @ExceptionHandler
    public Result handleSocketTimeoutException(SocketTimeoutException e) {
        log.error("连接超时", e);

        return Result.success();
    }
}
